from typing import Optional, Awaitable

import tornado.ioloop
import tornado.web
from tongsuo.tools import sm3_dgst, sm4_cbc_encrypt, sm4_cbc_decrypt, sm2_verify, sm2_sign


class IndexHandler(tornado.web.RequestHandler):
    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        pass

    def get(self):
        self.render("./html/index.html")


class SM3Handler(tornado.web.RequestHandler):
    def post(self):
        msg = self.get_body_argument('msg', 'world')
        self.write(sm3_dgst(msg))


class SM4EncryptHandler(tornado.web.RequestHandler):
    def post(self):
        msg = self.get_body_argument('msg', '')
        key = self.get_body_argument('key', '')
        self.write(sm4_cbc_encrypt(msg, key))


class SM4DecryptHandler(tornado.web.RequestHandler):
    def post(self):
        msg = self.get_body_argument('msg', '')
        key = self.get_body_argument('key', '')
        self.write(sm4_cbc_decrypt(msg, key))


if __name__ == "__main__":
    app = tornado.web.Application([
        (r"/", IndexHandler),
        (r"/sm3", IndexHandler),
        (r"/sm4", IndexHandler),
        (r"/sm3_dgst", SM3Handler),
        (r"/sm4_cbc_encrypt", SM4EncryptHandler),
        (r"/sm4_cbc_decrypt", SM4DecryptHandler),
        (r"/(.*)", tornado.web.StaticFileHandler, {"path": "./html/"}),
    ])
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
